package com.inspur.dgov.vlbod.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.inspur.dgov.vlbod.http.DgovResponse;
import com.inspur.dgov.vlbod.secure.constant.SecureConstant;
import com.inspur.dgov.vlbod.secure.token.TokenFactory;
import com.inspur.dgov.vlbod.secure.token.UserRecord;
import com.inspur.dgov.vlbod.weixin.WeiXinService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private WeiXinService weiXinService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 政务微信静默登录
     *
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/ssoLogin")
    public DgovResponse getUser(HttpServletRequest request, HttpServletResponse response) {
        JSONObject result = new JSONObject();
        try {
            String code = request.getParameter("code");

            // 获取企业微信access_token
            JSONObject tokenInfo = this.weiXinService.getToken();
            log.info("获取政务微信 access_token 成功：" + tokenInfo);

            // 获取政务微信登录用户标识
            String accessToken = tokenInfo.getString("access_token");
            JSONObject userBase = this.weiXinService.getUserId(code, accessToken);
            log.info("获取政务微信登录用户标识成功：" + userBase);

            // 获取政务微信登录用户详细信息
            String userId = userBase.getString("UserId");
            JSONObject user = this.weiXinService.getUserDetail(userId, accessToken);
            log.info("获取政务微信用户详细信息成功：" + user);

            // 生成登录令牌
            UserRecord userRecord = new UserRecord();
            userRecord.setUserId(user.getString("userid"));
            userRecord.setUserName(user.getString("name"));
            userRecord.setUserMobile(user.getString("mobile"));
            userRecord.setOrganCode("");
            JSONArray organs = user.getJSONArray("department");
            if (null != organs && organs.size() > 0) {
                userRecord.setOrganCode(organs.get(0).toString());
            }
            Map<String, Object> token = new HashMap<>();
            token.put("userMobile", userRecord.getUserMobile());
            token.put("organCode", userRecord.getOrganCode());
            String tokenStr = TokenFactory.createAccessToken(userRecord.getUserName(), userRecord.getUserId(), token);

            // 缓存令牌与用户信息（12小时有效）
            this.redisTemplate.opsForValue().set(SecureConstant.TOKEN_USER_KEY + tokenStr, userRecord, SecureConstant.USER_VALIDATE_TIME, TimeUnit.MINUTES);

            result.put("user", userRecord);
            result.put("token", tokenStr);
            return DgovResponse.success(result);
        } catch (Exception e) {
            log.error("/user/ssoLogin error:" + e.getMessage());
            return DgovResponse.fail("用户单点登录失败");
        }
    }

}
